<template>
  <div ref="chartRef" class="category-pie-chart"></div>
</template>

<script setup lang="ts">
import {ref, onMounted, onBeforeUnmount, watch} from 'vue'
import * as echarts from 'echarts'
import type {CategoryPie} from "@/api/statistics/type.ts";

interface Props {
  data: CategoryPie[]
  type: 'pie' | 'rose'
  title: string | '分类占比'

}

const props = defineProps<Props>()

const chartRef = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

const getCategoryColor = (index: number) => {
  const colors: Record<number, string> = {
    0: '#FF9F7F',
    1: '#F7CAC9',
    2: '#92A8D1',
    3: '#D2386C',
    4: '#45B8AC',
    5: '#B565A7',
    6: '#5B5EA6',
    7: '#9B2335',
    8: '#DD4124'
  }
  return colors[index] || '#6B5B95'
}

const renderChart = () => {
  let index = 0;
  if (!chartRef.value) return

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: props.data.map((item: CategoryPie) => item.name)
    },
    series: [
      {
        name: props.title,
        type: 'pie',
        radius: props.type === 'pie' ? ['50%', '70%'] : [30, 120],
        roseType: props.type === 'rose' ? 'area' : undefined,
        data: props.data.map((item: CategoryPie) => ({
          value: item.value,
          name: item.name,
          itemStyle: {
            color: getCategoryColor(index++)
          }
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          formatter: '{b}: {d}%'
        },
        labelLine: {
          show: true
        }
      }
    ]
  }

  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }

  chartInstance.setOption(option)
}

onMounted(() => {
  renderChart()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
})

const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

watch(() => props.type, renderChart)
watch(() => props.data, renderChart, {deep: true})
</script>

<style scoped lang="scss">
.category-pie-chart {
  width: 100%;
  height: 100%;
}
</style>
